package com.gui.lock.utils;

import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.UUID;
import java.util.concurrent.TimeUnit;


public class RedisLockWithTidProvider {

    private final StringRedisTemplate stringRedisTemplate;

    private final String tid;

    private static final String COMMON_KEY_PREFIX = "gui:";

    private final String key;

    public RedisLockWithTidProvider(StringRedisTemplate stringRedisTemplate, String businessType, String tid) {
        if (stringRedisTemplate == null) {
            throw new IllegalArgumentException("StringRedisTemplate cannot be null");
        }
        this.stringRedisTemplate = stringRedisTemplate;
        this.tid = tid;
        this.key = COMMON_KEY_PREFIX + businessType;
    }

    public boolean tryLock(long timeout) {
        Boolean lockFlag = stringRedisTemplate.opsForValue().setIfAbsent(key, this.tid, timeout, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(lockFlag);
    }


    public void unLock() {
        String threadId = stringRedisTemplate.opsForValue().get(key);
        if (this.tid.equals(threadId)) {
            stringRedisTemplate.delete(key);
        }
    }


}
